package org.iabako.server.serviceimpl.business;

import org.iabako.server.dao.JpaDAO;
import org.iabako.server.dao.business.ProductDAO;
import org.iabako.server.dao.business.QueryDefinitionDAO;
import org.iabako.server.tools.ServerTools;
import org.iabako.shared.entity.business.Product;
import org.iabako.shared.entity.enumeration.TrackingType;
import org.iabako.shared.iservice.business.StockService;
import org.iabako.shared.iservice.business.TrackingService;
import org.iabako.shared.querydefinition.SearchMotorQueryEnum;
import org.iabako.shared.querydefinition.columndefinition.ColumnDefinition;
import org.iabako.shared.querydefinition.columndefinition.ProductColumnEnum;
import org.iabako.shared.querydefinition.dto.QueryDefinitionDTO;
import org.iabako.shared.querydefinition.dto.QueryOperatorEnum;
import org.iabako.shared.tools.GenericTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Map;

/**
 * Created by jose on 17/01/15.
 */

@org.springframework.stereotype.Service("stockService")
public class StockServiceImpl extends AbstractServiceImpl implements StockService {

    @Autowired
    private ProductDAO productDAO;
    @Autowired
    QueryDefinitionDAO queryDefinitionDAO;
    @Autowired
    TrackingService trackingService;

    @Override
    protected JpaDAO getDAO() {
        return productDAO;
    }

    public QueryDefinitionDTO getSearchQueryDefinitionDTO(QueryDefinitionDTO qd) {
        qd.setSearchMotorQuery(SearchMotorQueryEnum.StockSearch);
        qd.addCriteria(ProductColumnEnum.productEnterprise, QueryOperatorEnum.IN, (ArrayList) getSessionUser().getEnterprise().getVisibleEnterprises());
        queryDefinitionDAO.executeQueryDefinition(qd);
        return qd;
    }

    public QueryDefinitionDTO setSearchCriteriaFromSuggest(QueryDefinitionDTO qd, Long hiddenSelectionCode, String suggestionValue) {
        if (!GenericTools.isEmpty(hiddenSelectionCode)) {
            qd.addCriteria(ProductColumnEnum.productId, QueryOperatorEnum.EQUALS, hiddenSelectionCode);
            return qd;
        }
        return setSearchCriteriaFromSuggest(qd,
                suggestionValue,
                new ColumnDefinition[]{ProductColumnEnum.number, ProductColumnEnum.name});
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveStockModifications(Map<Long, Double> stockModificationsMap) {
        for (Long productId : stockModificationsMap.keySet()) {
            Product product = (Product) getById(productId);
            product.setQuantity(ServerTools.round(product.getQuantity() + stockModificationsMap.get(productId)));

            trackingService.addTrackingToUserSession(TrackingType.stockModification, product);
            //Simple save
            save(product);
        }
    }
}
